package cc.rengu.redp.bizimpl.upmp.controller;

import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.ExtPropertyPlaceholderConfigurer;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//@MetaData("商户级限额管理")
@Controller
@RequestMapping(value = "/admin/quota/merchantLevelManager")
public class MerchantLevelQuotaManagetController {
    @Resource
    private ResourceLoader resourceLoader;
    @Autowired
    private MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    private MerchantGradeQuotaManagetService merchantGradeQuotaManagetService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;
    @Autowired
    private IUpmpOrganizationService iUpmpOrganizationService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpBMchntLevelInfoService bMchntLevelInfoService;
    @Autowired(required = false)
    private ExtPropertyPlaceholderConfigurer extPropertyPlaceholderConfigurer;
    private final static Logger log = LoggerFactory.getLogger(MerchantLevelQuotaManagetController.class);

    /**
     * 获取商户限额信息
     */
    @RequiresPermissions("merchantLevelManager:view")
    @ResponseBody
    @RequestMapping(value = "/getMerchantLevelList", method = RequestMethod.GET)
    public Page<BTxnLimitCfg> getMerchantLevelList(HttpServletRequest request) throws RedpException {
        Page<BTxnLimitCfg> merchantLeveList = null;
        try {
            merchantLeveList = merchantBaseInfoService.getMerchantLevelList(request);
        } catch (Exception e) {
            log.error("获取限额信息时系统异常:[{}]", e);
            throw new RedpException("获取限额信息时系统异常:"+e.getMessage());
        }
        return merchantLeveList;
    }

    /**
     * 保存商户限额配置
     */
    @RequiresPermissions("merchantLevelManager:add")
    @ResponseBody
    @RequestMapping(value = "saveMcQuota", method = RequestMethod.POST)
    public OperationResult saveMcQuota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) {

        try {
            txnCfginfo.setLimitType("11");//12-商户终端限额  //11-商户限额
            verfiyData(txnCfginfo);
            merchantBaseInfoService.saveMerchantQuotaInfo(txnCfginfo, request);
        } catch (Exception e) {
            log.error("保存商户限额信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult(e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }
    private void verfiyData(BTxnLimitCfg txnLimitCfgVo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnLimitCfgVo.getInstId());
        //     String instId = user.getInstId();
        String refundDayLimitAmt = txnLimitCfgVo.getRefundDayLimitAmt();
        String refundSingleLimitLoanMaxAmt = txnLimitCfgVo.getRefundSingleLimitLoanMaxAmt();
        if (StringUtils.isBlank(refundSingleLimitLoanMaxAmt)){
            refundSingleLimitLoanMaxAmt=txnLimitCfgVo.getReSingleLimitLoanMaxAmt();
        }
        String refundDayLimitLoanAmt = txnLimitCfgVo.getRefundDayLimitLoanAmt();
        String refundSingleLimitCredMaxAmt = txnLimitCfgVo.getRefundSingleLimitCredMaxAmt();
        if (StringUtils.isBlank(refundSingleLimitCredMaxAmt)){
            refundSingleLimitCredMaxAmt=txnLimitCfgVo.getReSingleLimitCredMaxAmt();
        }
        String refundDayLimitCredAmt = txnLimitCfgVo.getRefundDayLimitCredAmt();
        String mcNo = txnLimitCfgVo.getMchntNo();
        if (StringUtils.isBlank(mcNo)){
             mcNo = txnLimitCfgVo.getMcNo();
        }
        String mcTermNo = txnLimitCfgVo.getMcTermNo();

        String dayLimitAmt = txnLimitCfgVo.getDayLimitAmt();
        String monthLimitAmt = txnLimitCfgVo.getMonthLimitAmt();
        String dayLimitLoanAmt = txnLimitCfgVo.getDayLimitLoanAmt();
        String monthLimitLoanAmt = txnLimitCfgVo.getMonthLimitLoanAmt();
        String singleLimitLoanMaxAmt = txnLimitCfgVo.getSingleLimitLoanMaxAmt();
        String dayLimitCreditAmt = txnLimitCfgVo.getDayLimitCreditAmt();
        String monthLimitCreditAmt = txnLimitCfgVo.getMonthLimitCreditAmt();
        String singleLimitCreditMaxAmt = txnLimitCfgVo.getSingleLimitCreditMaxAmt();
        if(StringUtils.isBlank(mcNo)){
            throw  new RedpException("商户号不能为空");
        }
        BTxnLimitCfg marchantInfoByMcNo = merchantBaseInfoService.getMarchantInfoByMcNo(txnLimitCfgVo.getInstId(),mcNo);
        if(null==marchantInfoByMcNo||StringUtils.isBlank(marchantInfoByMcNo.getMchntLevelCode())){
            throw  new RedpException("获取商户信息异常");
        }
        if(StringUtils.isNotBlank(dayLimitAmt)&&StringUtils.isNotBlank(monthLimitAmt)){
            if(Double.parseDouble(dayLimitAmt)>Double.parseDouble(monthLimitAmt)){
                throw  new RedpException("日累计限额不能大于月累计限额");
            }
        }
        BTxnLimitCfg mcGradeQutaDetail = merchantGradeQuotaManagetService.getMcGradeQutaDetail(marchantInfoByMcNo.getMchntLevelCode(),txnLimitCfgVo.getInstId());

        if(null!=mcGradeQutaDetail){


            String dayLimitAmt1 = mcGradeQutaDetail.getDayLimitAmt();
            String monthLimitAmt1 = mcGradeQutaDetail.getMonthLimitAmt();
            String singleLimitLoanMaxAmt1 = mcGradeQutaDetail.getSingleLimitLoanMaxAmt();
            String dayLimitLoanAmt1 = mcGradeQutaDetail.getDayLimitLoanAmt();
            String monthLimitLoanAmt1 = mcGradeQutaDetail.getMonthLimitLoanAmt();
            String singleLimitCreditMaxAmt1 = mcGradeQutaDetail.getSingleLimitCreditMaxAmt();
            String dayLimitCreditAmt1 = mcGradeQutaDetail.getDayLimitCreditAmt();
            String monthLimitCreditAmt1 = mcGradeQutaDetail.getMonthLimitCreditAmt();
            if(StringUtils.isNotBlank(dayLimitAmt1)&&StringUtils.isNotBlank(dayLimitAmt)){
                if(Double.parseDouble(dayLimitAmt)>Double.parseDouble(dayLimitAmt1)){
                    throw  new RedpException("日累计限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(monthLimitAmt1)&&StringUtils.isNotBlank(monthLimitAmt)){
                if(Double.parseDouble(monthLimitAmt)>Double.parseDouble(monthLimitAmt1)){
                    throw  new RedpException("月累计限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(singleLimitLoanMaxAmt1)&&StringUtils.isNotBlank(singleLimitLoanMaxAmt)){
                if(Double.parseDouble(singleLimitLoanMaxAmt)>Double.parseDouble(singleLimitLoanMaxAmt1)){
                    throw  new RedpException("单笔最大借记限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(dayLimitLoanAmt1)&&StringUtils.isNotBlank(dayLimitLoanAmt)){
                if(Double.parseDouble(dayLimitLoanAmt)>Double.parseDouble(dayLimitLoanAmt1)){
                    throw  new RedpException("日累计借记限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(monthLimitLoanAmt1)&&StringUtils.isNotBlank(monthLimitLoanAmt)){
                if(Double.parseDouble(monthLimitLoanAmt)>Double.parseDouble(monthLimitLoanAmt1)){
                    throw  new RedpException("月累计限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(singleLimitCreditMaxAmt1)&&StringUtils.isNotBlank(singleLimitCreditMaxAmt)){
                if(Double.parseDouble(singleLimitCreditMaxAmt)>Double.parseDouble(singleLimitCreditMaxAmt1)){
                    throw  new RedpException("单笔最大贷记限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(dayLimitCreditAmt1)&&StringUtils.isNotBlank(dayLimitCreditAmt)){
                if(Double.parseDouble(dayLimitCreditAmt)>Double.parseDouble(dayLimitCreditAmt1)){
                    throw  new RedpException("日累计贷记限额 商户限额不能大于商户等级限额");
                }
            }
            if(StringUtils.isNotBlank(monthLimitCreditAmt1)&&StringUtils.isNotBlank(monthLimitCreditAmt)){
                if(Double.parseDouble(monthLimitCreditAmt)>Double.parseDouble(monthLimitCreditAmt1)){
                    throw  new RedpException("月累计贷记限额 商户限额不能大于商户等级限额");
                }
            }
        }
        /*else {
            throw new RedpException("需要先配置商户:"+mcNo+"商户等级限额");
        }*/


        if("12".equals(txnLimitCfgVo.getLimitType())){

            if(StringUtils.isBlank(mcTermNo)){
                throw  new RedpException("终端编号不能为空");
            }
        }else if("11".equals(txnLimitCfgVo.getLimitType())){


            if(StringUtils.isNotBlank(refundDayLimitAmt)&&StringUtils.isNotBlank(refundDayLimitLoanAmt)){
                if(Double.parseDouble(refundDayLimitLoanAmt)>Double.parseDouble(refundDayLimitAmt)){
                    throw  new RedpException("日累计借记退款限额不能大于日累计退款限额");
                }
            }
            if(StringUtils.isNotBlank(refundDayLimitAmt)&&StringUtils.isNotBlank(refundDayLimitCredAmt)){
                if(Double.parseDouble(refundDayLimitCredAmt)>Double.parseDouble(refundDayLimitAmt)){
                    throw  new RedpException("日累计贷记退款限额不能大于日累计退款限额");
                }
            }
            if(StringUtils.isNotBlank(refundDayLimitLoanAmt)&&StringUtils.isNotBlank(refundSingleLimitLoanMaxAmt)){
                if(Double.parseDouble(refundSingleLimitLoanMaxAmt)>Double.parseDouble(refundDayLimitLoanAmt)){
                    throw  new RedpException("单笔借记退款限额不能大于日累计借记退款限额");
                }
            }
            if(StringUtils.isNotBlank(refundDayLimitCredAmt)&&StringUtils.isNotBlank(refundSingleLimitCredMaxAmt)){
                if(Double.parseDouble(refundSingleLimitCredMaxAmt)>Double.parseDouble(refundDayLimitCredAmt)){
                    throw  new RedpException("单笔贷记退款限额不能大于日累计贷记退款限额");
                }
            }
            if(StringUtils.isNotBlank(refundDayLimitAmt)&&StringUtils.isNotBlank(refundSingleLimitCredMaxAmt)){
                if(Double.parseDouble(refundSingleLimitCredMaxAmt)>Double.parseDouble(refundDayLimitAmt)){
                    throw  new RedpException("单笔贷记退款限额不能大于日累计退款限额");
                }
            }
            if(StringUtils.isNotBlank(refundDayLimitAmt)&&StringUtils.isNotBlank(refundSingleLimitLoanMaxAmt)){
                if(Double.parseDouble(refundSingleLimitLoanMaxAmt)>Double.parseDouble(refundDayLimitAmt)){
                    throw  new RedpException("单笔借记退款限额不能大于日累计退款限额");
                }
            }
        }




        //------日累计限额

        if(StringUtils.isNotBlank(dayLimitAmt)&&StringUtils.isNotBlank(dayLimitLoanAmt)){
            if(Double.parseDouble(dayLimitLoanAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("日累计借记限额不能大于日累计限额");
            }
        }
        if(StringUtils.isNotBlank(dayLimitAmt)&&StringUtils.isNotBlank(singleLimitLoanMaxAmt)){
            if(Double.parseDouble(singleLimitLoanMaxAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("单笔借记限额不能大于日累计限额");
            }
        }
        if(StringUtils.isNotBlank(dayLimitAmt)&&StringUtils.isNotBlank(dayLimitCreditAmt)){
            if(Double.parseDouble(dayLimitCreditAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("日累计贷记限额不能大于日累计限额");
            }
        }
        if(StringUtils.isNotBlank(dayLimitAmt)&&StringUtils.isNotBlank(singleLimitCreditMaxAmt)){
            if(Double.parseDouble(singleLimitCreditMaxAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("单笔贷记限额不能大于日累计限额");
            }
        }
        //-----月累计限额
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(monthLimitLoanAmt)){
            if(Double.parseDouble(monthLimitLoanAmt)>Double.parseDouble(monthLimitAmt)){
                throw  new RedpException("月累计借记限额不能大于月累计限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(dayLimitLoanAmt)){
            if(Double.parseDouble(dayLimitLoanAmt)>Double.parseDouble(monthLimitAmt)){
                throw  new RedpException("日累计借记限额不能大于月累计限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(singleLimitLoanMaxAmt)){
            if(Double.parseDouble(singleLimitLoanMaxAmt)>Double.parseDouble(monthLimitAmt)){
                throw  new RedpException("单笔借记限额不能大于月累计限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(monthLimitCreditAmt)){
            if(Double.parseDouble(monthLimitCreditAmt)>Double.parseDouble(monthLimitAmt)){
                throw  new RedpException("月累计贷记限额不能大于月累计限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(dayLimitCreditAmt)){
            if(Double.parseDouble(dayLimitCreditAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("日累计贷记限额不能大于月累计限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitAmt)&&StringUtils.isNotBlank(singleLimitCreditMaxAmt)){
            if(Double.parseDouble(singleLimitCreditMaxAmt)>Double.parseDouble(dayLimitAmt)){
                throw  new RedpException("单笔贷记限额不能大于月累计限额");
            }
        }

        //-------借记
        if(StringUtils.isNotBlank(monthLimitLoanAmt)&&StringUtils.isNotBlank(dayLimitLoanAmt)){
            if(Double.parseDouble(dayLimitLoanAmt)>Double.parseDouble(monthLimitLoanAmt)){
                throw  new RedpException("日累计借记限额不能大于月累计借记限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitLoanAmt)&&StringUtils.isNotBlank(singleLimitLoanMaxAmt)){
            if(Double.parseDouble(singleLimitLoanMaxAmt)>Double.parseDouble(monthLimitLoanAmt)){
                throw  new RedpException("单笔借记限额不能大于月累计借记限额");
            }
        }
        if(StringUtils.isNotBlank(dayLimitLoanAmt)&&StringUtils.isNotBlank(singleLimitLoanMaxAmt)){
            if(Double.parseDouble(singleLimitLoanMaxAmt)>Double.parseDouble(dayLimitLoanAmt)){
                throw  new RedpException("单笔借记限额不能大于日累计借记限额");
            }
        }
        //-------贷记
        if(StringUtils.isNotBlank(monthLimitCreditAmt)&&StringUtils.isNotBlank(dayLimitCreditAmt)){
            if(Double.parseDouble(dayLimitCreditAmt)>Double.parseDouble(monthLimitCreditAmt)){
                throw  new RedpException("日累计贷记限额不能大于月累计贷记限额");
            }
        }
        if(StringUtils.isNotBlank(monthLimitCreditAmt)&&StringUtils.isNotBlank(singleLimitCreditMaxAmt)){
            if(Double.parseDouble(singleLimitCreditMaxAmt)>Double.parseDouble(monthLimitCreditAmt)){
                throw  new RedpException("单笔贷记限额不能大于月累计贷记限额");
            }
        }
        if(StringUtils.isNotBlank(dayLimitCreditAmt)&&StringUtils.isNotBlank(singleLimitCreditMaxAmt)){
            if(Double.parseDouble(singleLimitCreditMaxAmt)>Double.parseDouble(dayLimitCreditAmt)){
                throw  new RedpException("单笔贷记限额不能大于日累计贷记限额");
            }
        }
    }

    /**
     * 获取商户信息
     */
    @RequiresPermissions("merchantLevelManager:view")
    @ResponseBody
    @RequestMapping(value = "/selectMchntNoLevel", method = RequestMethod.GET)
    public OperationResult selectMchntLevel(HttpServletRequest request) {
        String MchntNoLevel = "";
        String mchntNo = request.getParameter("mchntNo");
        if (StringUtils.isBlank(mchntNo)){
            mchntNo=request.getParameter("mcNo");
        }
        String instId = request.getParameter("instId");
        List<BTxnLimitCfg> txnLimitCfgVos = null;
        try {
            UpmpBMchntBaseInfo bymchntno = bMchntBaseInfoService.findByMchntNo(mchntNo);
            String mchntLevel = bymchntno.getMchntLevel();
            UpmpBMchntLevelInfo mchntlevelinfo = bMchntLevelInfoService.findOneByCode(mchntLevel, "01", instId);
            if (Common.isNotBlank(mchntlevelinfo)) {
                txnLimitCfgVos=merchantGradeQuotaManagetService.queryBankGradeQuota(instId, mchntlevelinfo.getMchntLevelCode());
            }

            if(CollectionUtils.isEmpty(txnLimitCfgVos)){
                return OperationResult.buildFailureResult("商户等级限额不存在");
            }
        } catch (Exception e) {
            log.error("获取商户等级时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("获取商户等级时系统异常");
        }
        return OperationResult.buildSuccessResult(txnLimitCfgVos);
    }
    /**
     * 保存终端限额配置
     */
    @RequiresPermissions("merchantLevelManager:add")
    @ResponseBody
    @RequestMapping(value = "/saveMcTremQuota", method = RequestMethod.POST)
    public OperationResult saveMcTremQuota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) {

        try {
            txnCfginfo.setLimitType("12");//12-商户终端限额  //11-商户限额
            verfiyData(txnCfginfo);
            merchantBaseInfoService.saveMcTremQuota(txnCfginfo, request);
        } catch (Exception e) {
            log.error("保存终端限额信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("保存终端限额信息时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }
    /**
     * 修改终端限额数据
     */
    @RequiresPermissions("merchantLevelManager:edit")
    @ResponseBody
    @RequestMapping(value = "editTmQuota", method = RequestMethod.POST)
    public OperationResult editTmQuota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) {

        try {
            txnCfginfo.setLimitType("12");//12-商户终端限额  //11-商户限额

            verfiyData(txnCfginfo);
            merchantBaseInfoService.editTmQuota(txnCfginfo);
        } catch (Exception e) {
            log.error("修改终端限额配置时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("修改终端限额配置时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }

    //----------------停用 启用 注销
    /**
     *停用
     */
    @RequiresPermissions("merchantLevelManager:stop")
    @ResponseBody
    @RequestMapping(value = "stopMcLevelQuota",method = RequestMethod.PUT)
    public OperationResult stopMcLevelQuota(HttpServletRequest request, BTxnLimitCfg txnCfginfo){

        try {
            merchantBaseInfoService.stopMcLevelQuota(request,txnCfginfo);
        } catch (Exception e) {
            log.error("保存限额操作信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("保存限额操作信息时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }
    /**
     *启用
     */
    @RequiresPermissions("merchantLevelManager:use")
    @ResponseBody
    @RequestMapping(value = "startMcLevelQuota",method = RequestMethod.PUT)
    public OperationResult startMcLevelQuota(HttpServletRequest request, BTxnLimitCfg txnCfginfo){

        try {
            merchantBaseInfoService.startMcLevelQuota(request,txnCfginfo);
        } catch (Exception e) {
            log.error("保存限额操作信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("保存限额操作信息时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }
    /**
     *注销
     */
    @RequiresPermissions("merchantLevelManager:cancel")
    @ResponseBody
    @RequestMapping(value = "deleteMcLevelQuota",method = RequestMethod.PUT)
    public OperationResult deleteMcLevelQuota(HttpServletRequest request, BTxnLimitCfg txnCfginfo){

        try {
            merchantBaseInfoService.deleteMcLevelQuota(request,txnCfginfo);
        } catch (Exception e) {
            log.error("保存限额操作信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("保存限额操作信息时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }

    /**
     * 获取终端限额数据
     */
    @RequiresPermissions("merchantLevelManager:edit")
    @ResponseBody
    @RequestMapping(value = "/getTermQuotaList", method = RequestMethod.GET)
    public Page<BTxnLimitCfg> getTermQuotaList(BTxnLimitCfg request) throws RedpException {
        Page<BTxnLimitCfg> termQuotaList = null;
        try {
            String mcNo = request.getMcNo();
            if (StringUtils.isBlank(mcNo)){
                mcNo=request.getMchntNo();
            }
            termQuotaList = merchantBaseInfoService.getTermQuotaList(mcNo, request);
        } catch (Exception e) {
            log.error("获取限额信息时系统异常:[{}]", e);
            throw new RedpException("获取限额信息时系统异常");
        }

        return termQuotaList;
    }
    /**
     * 修改商户限额配置
     */
    @RequiresPermissions("merchantLevelManager:edit")
    @ResponseBody
    @RequestMapping(value = "editMcQuota", method = RequestMethod.PUT)
    public OperationResult editMcQuota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) {

        try {
            txnCfginfo.setLimitType("11");//12-商户终端限额  //11-商户限额
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
//            if(user.isAdmin()){
//                txnCfginfo.setInstId(request.getParameter("instId"));
//            }else{
//                txnCfginfo.setInstId(user.getInstId());
//            }

            verfiyData(txnCfginfo);
            merchantBaseInfoService.editMcQuota(txnCfginfo);
        } catch (Exception e) {
            log.error("修改商户限额配置时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("修改商户限额配置时系统异常:"+e.getMessage());
        }
        return OperationResult.buildSuccessResult();
    }

    /**
     * 生成 Excel导入模板
     *
     * @param response
     */
    @PostMapping("getExcel")
    public void generateImportTemplate(HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String filename = "merchantQuotaImportTemplate.xlsx";
            String path = "template/merchantQuotaImportTemplate.xlsx";
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                // jvm的垃圾回收
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 导入Excel数据
     * @param excelFile
     * @return
     * @throws Exception
     */
    @RequiresPermissions("merchantLevelManager:import")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult uploadDataFromExcel(@RequestParam("file") MultipartFile excelFile,HttpServletRequest request) throws Exception {

        try {

            String originalFilename = excelFile.getOriginalFilename();
            if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
                log.error("文件不是excel类型");
                return OperationResult.buildFailureResult("文件不是excel类型");
            }
            UpmpSysParam dataDict = upmpSysParamService.findChildrenByPrimaryKeyAndParent("MCHNT_IMPORT_PARAM",
                    BusinessContainer.SYS_IMPORT_EXPORT_PARAM, request.getParameter("instId"), null);
           // DataDict dataDict = dataDictService.findChildrenByPrimaryKey("MCHNT_IMPORT_PARAM", BusinessContainer.SYS_IMPORT_EXPORT_PARAM);
            if(Common.isBlank(dataDict)){
                log.error("解析文件时获取系统参数失败，请联系系统管理员");
                throw new RedpException("解析文件时获取系统参数失败，请联系系统管理员");
            }
            if(Common.isBlank(dataDict.getRichtextValue())){
                log.error("解析文件时获取系统参数值失败，请联系系统管理员");
                throw new RedpException("解析文件时获取系统参数值失败，请联系系统管理员");
            }
            Map sysparam = (Map) JSON.parse(dataDict.getRichtextValue());

            int maxRecords = Common.isBlank(sysparam.get("MAX_RECORDS"))?Integer.valueOf(extPropertyPlaceholderConfigurer.getProperty("MCHNT_IMPORT_MAX_RECORDS")):Integer.valueOf(sysparam.get("MAX_RECORDS").toString());
            ArrayList<BTxnLimitCfg> bankLevelQuotaList = new ArrayList<>();
            Workbook workbook =null;
            if(originalFilename.endsWith(".xlsx")){
                workbook=new XSSFWorkbook(excelFile.getInputStream());
            }else if(originalFilename.endsWith(".xls")){
                workbook=new HSSFWorkbook(excelFile.getInputStream());
            }

            Sheet sheetAt = workbook.getSheetAt(0);
            int lastRowNum = sheetAt.getLastRowNum();
            if(lastRowNum < 1){
                return OperationResult.buildFailureResult("数据导入失败:数据为空");
            }
            if(maxRecords<lastRowNum){
                log.error("导入文件中限额信息记录数超过{}！",maxRecords);
                throw new RedpException("导入文件中限额信息记录数超过"+maxRecords+"！");
            }
            //校验模板是否正确
            verifyTable(sheetAt.getRow(0));
            List<BTxnLimitCfg> merchantBaseInfoList = merchantBaseInfoService.getNotAddMCInfo(request.getParameter("instId"));
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(request.getParameter("instId"));
            String instId = "";
            String crtOrgId = "";
            if(user.isAdmin()){
                instId = request.getParameter("instId");
                UpmpOrganization headOrg = iUpmpOrganizationService.getHeadOrgByCode(instId);
                crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
            }else{
                instId = user.getInstId();
                crtOrgId = user.getOrgCode();
            }
            for (int i = 1; i <= lastRowNum; i++) {
                BTxnLimitCfg bankLevelQuota = new BTxnLimitCfg();
                Row rowTitle = sheetAt.getRow(i);
                if (rowTitle != null) {// 行不为空
                    // 读取cell


                    bankLevelQuota.setMchntNo(CommonUtils.getValue(rowTitle.getCell(0)));
                    bankLevelQuota.setLimitInst(bankLevelQuota.getMchntNo());
                    bankLevelQuota.setMcNo(bankLevelQuota.getMchntNo());
                    bankLevelQuota.setDayLimitAmt(CommonUtils.getValue(rowTitle.getCell(1)));
                    bankLevelQuota.setMonthLimitAmt(CommonUtils.getValue(rowTitle.getCell(2) ));
                    bankLevelQuota.setSingleLimitLoanMaxAmt(CommonUtils.getValue(rowTitle.getCell(3) ));
                    bankLevelQuota.setDayLimitLoanAmt(CommonUtils.getValue(rowTitle.getCell(4) ));
                    bankLevelQuota.setMonthLimitLoanAmt(CommonUtils.getValue(rowTitle.getCell(5) ));
                    bankLevelQuota.setSingleLimitCreditMaxAmt(CommonUtils.getValue(rowTitle.getCell(6) ));
                    bankLevelQuota.setDayLimitCreditAmt(CommonUtils.getValue(rowTitle.getCell(7) ));
                    bankLevelQuota.setMonthLimitCreditAmt(CommonUtils.getValue(rowTitle.getCell(8) ));
                    bankLevelQuota.setRefundDayLimitAmt(CommonUtils.getValue(rowTitle.getCell(9) ));
                    bankLevelQuota.setRefundSingleLimitLoanMaxAmt(CommonUtils.getValue(rowTitle.getCell(10) ));
                    bankLevelQuota.setRefundDayLimitLoanAmt(CommonUtils.getValue(rowTitle.getCell(11) ));
                    bankLevelQuota.setRefundSingleLimitCredMaxAmt(CommonUtils.getValue(rowTitle.getCell(12) ));
                    bankLevelQuota.setRefundDayLimitCredAmt(CommonUtils.getValue(rowTitle.getCell(13) ));
                    bankLevelQuota.setLimitType("11");
                    bankLevelQuota.setInstId(instId);
                    bankLevelQuota.setCrtOrgId(crtOrgId);
                    if(StringUtils.isBlank(bankLevelQuota.getMcNo())){
                        throw new RedpException("第"+i+"行数据商户号为空");
                    }
                    verfiyMcNo(bankLevelQuota.getMcNo(),merchantBaseInfoList);
                    verfiyData(bankLevelQuota);
                    bankLevelQuotaList.add(bankLevelQuota);
                }
            }
            merchantBaseInfoService.batchUploadBankQuotal(bankLevelQuotaList,instId);
        } catch (RedpException e) {
            return OperationResult.buildFailureResult("数据导入失败:"+e.getMessage());
        }catch (RuntimeException e) {
            return OperationResult.buildFailureResult("数据导入失败:系统异常");
        }
        return OperationResult.buildSuccessResult("数据导入成功");
    }

    private void verfiyMcNo(String mcNo, List<BTxnLimitCfg> merchantBaseInfoList) throws RedpException {

       /*merchantBaseInfoList.forEach((e)->{
           if(mcNo.equals(e.getMchntNo())){
               return ;
           }
       });*/
        if(CollectionUtils.isNotEmpty(merchantBaseInfoList)){
            for(BTxnLimitCfg marchantbaseinfo:merchantBaseInfoList){
                String mchntNo = marchantbaseinfo.getMchntNo();
                if (StringUtils.isBlank(mchntNo)){
                    mchntNo=marchantbaseinfo.getMcNo();
                }
                if(mchntNo.equals(mcNo)){
                    return;
                }
            }

        }
        throw new RedpException("该商户号商户信息不存在或限额信息已添加:"+mcNo);
    }
    private void verifyTable(Row row) throws RedpException {
        String value = CommonUtils.getValue(row.getCell(0));
        if(!("商户号".equals(CommonUtils.getValue(row.getCell(0))))){
            throw new RedpException("导入模板不匹配");
        }

        if(!("日累计限额".equals(CommonUtils.getValue(row.getCell(1))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("月累计限额".equals(CommonUtils.getValue(row.getCell(2))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("单笔借记限额".equals(CommonUtils.getValue(row.getCell(3))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("日累计借记限额".equals(CommonUtils.getValue(row.getCell(4))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("月累计借记限额".equals(CommonUtils.getValue(row.getCell(5))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("单笔贷记限额".equals(CommonUtils.getValue(row.getCell(6))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("日累计贷记限额".equals(CommonUtils.getValue(row.getCell(7))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("月累计贷记限额".equals(CommonUtils.getValue(row.getCell(8))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("日累计限额(退款限额)".equals(CommonUtils.getValue(row.getCell(9))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("单笔借记限额(退款限额)".equals(CommonUtils.getValue(row.getCell(10))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("单笔贷记限额(退款限额)".equals(CommonUtils.getValue(row.getCell(11))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("日累计借记限额(退款限额)".equals(CommonUtils.getValue(row.getCell(12))))){
            throw new RedpException("导入模板不匹配");
        }
        if(!("日累计贷记限额(退款限额)".equals(CommonUtils.getValue(row.getCell(13))))){
            throw new RedpException("导入模板不匹配");
        }
    }
    /**
     * 获取未配置限额的termNoList
     */
    @RequiresPermissions("merchantLevelManager:add")
    @ResponseBody
    @RequestMapping(value = "/getAddTermNoList", method = RequestMethod.GET)
    public OperationResult getAddTermNoList(HttpServletRequest request) {
        List<BTxnLimitCfg> termInfo = null;
        try {
            String q = request.getParameter("q");
            if (null == q) {
                return null;
            }
            q = q.replaceAll("&amp;", "&");
            String[] param = q.split("&");
            String instId = "";
            if (null != param && param.length > 1) {
                if (Common.isNotBlank(param[1])) {
                    instId = param[1];
                }
            }
            String mcNo = request.getParameter("mcNo");
            String opp=request.getParameter("opp");
            termInfo = merchantBaseInfoService.getAddTermNoList(mcNo,instId,opp);
        } catch (Exception e) {
            log.error("获取限额信息时系统异常:[{}]", e);
            OperationResult.buildFailureResult("获取限额信息时系统异常");
        }
        OperationResult operationResult = OperationResult.buildSuccessResult();
        operationResult.setData(termInfo);
        return operationResult;
    }
}
